// user.js
var api = require('../../api.js');
var app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
      contact_tel: "",
      show_customer_service: 0,
      order_count:{},//各个状态的订单数量
      isDistributor:false,//当前用户是否为经销商
      goods_qrcode:"",
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
    },
    redirectPage(e){
      let self = this;
      let backurl = e.currentTarget.dataset.url;
      let token = wx.getStorageSync("token");
      if(!token){
        wx.navigateTo({
          url: '/pages/allow/allow',
          events: {
            acceptDataFromOpenedPage(data) {
              console.log(data);
              if (data.hasLogin) {
                wx.navigateBack();
                if (backurl) {
                  setTimeout(() => {
                    wx.navigateTo({
                      url: backurl,
                    })
                  }, 300)
                }
              }
            }
          },
          success: function (res) {
            res.eventChannel.emit('acceptDataFromOpenerPage', { url: backurl })
          }
        })
        // // 查看是否授权，已授权的，看看是否已经绑定手机，已经绑定的自动登陆，否则绑定手机然后再进行登陆
        // wx.getSetting({
        //   success(res) {
        //     let hasUserInfo = res.authSetting['scope.userInfo'];//是否授权
        //     let token = wx.getStorageSync('token');
        //     if (hasUserInfo) {  //已授权
        //       wx.getUserInfo({  // 已经授权，可以直接调用 getUserInfo 获取头像昵称
        //         success: function (res) {
        //           console.log(res);
        //           self.setData({
        //             userInfo: res.rawData,
        //             isUserInfoAuth: true
        //           });
        //           app.login(true, null,  self.redirect, { url: backurl});//用户登录
        //         }
        //       });
        //     }else{
              
        //     }
        //   }
        // }) 
      }else{
        wx.navigateTo({
          url: backurl,
        })
      }
    },
    redirectH5Page(e){
      let redirecturl =  e.currentTarget.dataset.url;
      if(api._api_root === 'https://www.tokyolifestyle.com/portal/'){//两个小程序访问地址不同
        redirecturl = 'https://reiwatakiya-1300674810.cos.ap-chengdu.myqcloud.com/newuser-baoyou.html'
      }
      wx.navigateTo({
        url: '/pages/xinren/baoyou/baoyou?htmlUrl='+redirecturl,
      })
    },
    getQrcode: function () {
      var page = this;
      page.setData({
        goods_qrcode_active: "active",
        share_modal_active: "",
      });
      if (page.data.goods_qrcode)
          return true;
      app.request({
        url: api.share.getShareQrcode,
        method:'post',
        data: {
          path:'pages/index/index',
          appid:api.APPID,
          //orderId: page.data.id,
        },
        success: function (res) {
          if (res.code == 200) {
            page.setData({
              goods_qrcode: res.data,
            });
          }
        },
      });
    },
    saveGoodsQrcode: function () {
      var page = this;
      if (!wx.saveImageToPhotosAlbum) {
        // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
        wx.showModal({
          title: '提示',
          content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。',
          showCancel: false,
        });
        return;
      }
  
      wx.showLoading({
        title: "正在保存图片",
        mask: false,
      });
  
      wx.downloadFile({
        url: page.data.goods_qrcode,
        success: function (e) {
          wx.showLoading({
            title: "正在保存图片",
            mask: false,
          });
          wx.saveImageToPhotosAlbum({
            filePath: e.tempFilePath,
            success: function () {
              wx.showModal({
                title: '提示',
                content: '二维码保存成功',
                showCancel: false,
              });
            },
            fail: function (e) {
              // wx.showModal({
              //   title: '图片保存失败',
              //   content: e.errMsg,
              //   showCancel: false,
              // });
            },
            complete: function (e) {
              console.log(e);
              wx.hideLoading();
            }
          });
        },
        fail: function (e) {
          wx.showModal({
            title: '图片下载失败',
            content: e.errMsg + ";" + page.data.goods_qrcode,
            showCancel: false,
          });
        },
        complete: function (e) {
          console.log(e);
          wx.hideLoading();
        }
      });
    },
    goodsQrcodeClose: function () {
      var page = this;
      page.setData({
        goods_qrcode_active: "",
        no_scroll: false,
      });
    },
    loadData: function (options) {
      var page = this;
      var hasMemberInfo = wx.getStorageSync("hasMemberInfo");
      page.setData({
        hasMemberInfo: hasMemberInfo,
      });
      if (hasMemberInfo){
        page.getMemberInfo();
      }
    },
    getMemberInfo:function(){
      let page = this;
      app.request({
        url: api.user.getMemberInfo,
        success:function(res){
          if (res.code == 200) {
            console.log(res.data)
            wx.setStorageSync('user_info', res.data);
            let orderNum = res.data.orderStatistics;
            let temporder_count = {};
            if (!orderNum){
              temporder_count = null;
            }else{
              orderNum.map((item, index) => {
                temporder_count['status' + item.status] = item.count;
              })
            }
            
            console.log(temporder_count);
            page.setData({
              'user_info': res.data,
              order_count: temporder_count
            })
          }else{
            wx.showToast({
              title: '请稍后再试',
              icon:'none',
              duration:1500
            })
          }
        }
      })
    },
    userLogout(){
      let page = this;
      wx.showModal({
        title: '提示',
        content: '确定要退出吗？',
        success (res) {
          if (res.confirm) {
            wx.clearStorageSync();
            page.setData({
              hasMemberInfo:false,
              user_info:{},
              order_count:{},
              isDistributor:false,
            })
          } 
        }
      })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        var page = this;
        let token = wx.getStorageSync('token');
        if(token){
          page.loadData();
          app.checkUserIditity(function(data){
            if(data.distributor){
              page.setData({
                isDistributor:true,
              })
            }
          })
        }
    },

    callTel: function (e) {
        var tel = e.currentTarget.dataset.tel;
        wx.makePhoneCall({
            phoneNumber: tel, //仅为示例，并非真实的电话号码
        });
    },
    apply: function (e) {
        var page = this;
        var share_setting = wx.getStorageSync("share_setting");
        var user_info = wx.getStorageSync("user_info");
        if (share_setting.share_condition == 1) {
            wx.navigateTo({
                url: '/pages/add-share/index',
            })
        } else if (share_setting.share_condition == 0) {
            if (user_info.is_distributor == 0) {
                wx.showModal({
                    title: "申请成为分销商",
                    content: "是否申请？",
                    success: function (r) {
                        if (r.confirm) {
                            wx.showLoading({
                                title: "正在加载",
                                mask: true,
                            });
                            app.request({
                                url: api.share.join,
                                methods: "POST",
                                success: function (res) {
                                    if (res.code == 200) {
                                        user_info.is_distributor = 2;
                                        wx.setStorageSync("user_info", user_info);
                                    }
                                },
                                complete: function () {
                                    wx.hideLoading();
                                    wx.navigateTo({
                                        url: '/pages/add-share/index',
                                    })
                                }
                            });
                        }
                    },
                })
            } else {
                wx.navigateTo({
                    url: '/pages/add-share/index',
                })
            }
        }
    },
    verify:function(e){
      wx.scanCode({
        onlyFromCamera:false,
        success: function (res) {
          console.log(res)
          wx.navigateTo({
            url: '/'+res.path,
          })
        },fail:function(e){
          wx.showToast({
            title:'失败'
          });
        }
      });
    }
});